package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.AddressBook;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/user/addressBook")
@Api(tags = "地址簿接口")
@RestController
public class UserAddressBookController {

    @Autowired
    private AddressBookService addressBookService;
    @PostMapping
    @ApiOperation("新增地址")
    public Result AddAddress(@RequestBody AddressBook addressBook,
                             @RequestHeader("authentication") String authorizationHeader){
        String token = authorizationHeader.replace("Bearer ", "");
        Long userId;

        JwtProperties jwtProperties  = new JwtProperties();
        try {
            // 解析 JWT，以获取用户信息
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);  // 解析 JWT
            userId = claims.get(JwtClaimsConstant.USER_ID, Long.class);
        } catch (Exception e) {
            // 返回错误处理的信息，例如 Token 无效、解析失败等
            return Result.error("无效的 token: " + e.getMessage());
        }

        addressBook.setUserId(userId);
        addressBook.setIsDefault(0);

        addressBookService.AddAddress(addressBook);
        return Result.success();
    }

    /**
     * 查询当前登录用户的所有地址信息
     * @param authorizationHeader
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> GetAddressBookList(@RequestHeader("authentication") String authorizationHeader){

        String token = authorizationHeader.replace("Bearer ", "");
            Long userId;

            JwtProperties jwtProperties  = new JwtProperties();
            try {
                // 解析 JWT，以获取用户信息
                Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);  // 解析 JWT
                userId = claims.get(JwtClaimsConstant.USER_ID, Long.class);
            } catch (Exception e) {
                // 返回错误处理的信息，例如 Token 无效、解析失败等
                return Result.error("无效的 token: " + e.getMessage());
            }

            List<AddressBook> addressBooks = addressBookService.GetAddressBookList(userId);
            return Result.success(addressBooks);
    }

    /**
     * 查询默认地址
     * @param authorizationHeader
     * @return
     */
    @GetMapping("/default")
    @ApiOperation("查询默认地址")
    public Result<AddressBook> GetAddressBookDefault(@RequestHeader("authentication") String authorizationHeader){

        String token = authorizationHeader.replace("Bearer ", "");
        Long userId;

        JwtProperties jwtProperties  = new JwtProperties();
        try {
            // 解析 JWT，以获取用户信息
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);  // 解析 JWT
            userId = claims.get(JwtClaimsConstant.USER_ID, Long.class);
        } catch (Exception e) {
            // 返回错误处理的信息，例如 Token 无效、解析失败等
            return Result.error("无效的 token: " + e.getMessage());
        }

        AddressBook addressBooks = addressBookService.GetAddressBookDefault(userId);
        if (addressBooks!=null){
            return Result.success(addressBooks);
        }else {
            return Result.success();
        }

    }

    /**
     * 根据id修改地址
     * @return
     */
    @PutMapping()
    @ApiOperation("根据id修改地址")
    public Result UpdateAddressBook(@RequestBody AddressBook addressBook){
        addressBookService.UpdateAddressBook(addressBook);
        return Result.success();
    }

    /**
     * 根据id删除地址
     * @return
     */
    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result UpdateAddressBook(@RequestBody Integer id){
        addressBookService.deleteAddressBook(id);
        return Result.success();
    }

    /**
     * 根据id查询地址
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getAddressBookById(@PathVariable Integer id){
        AddressBook addressBook=addressBookService.getAddressBookById(id);
        return Result.success(addressBook);
    }


    /**
     * 设置默认地址
     * @return
     */
    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setAddressBookDefault(@RequestBody Integer id){
        addressBookService.setAddressBookDefault(id);
        return Result.success();
    }
}
